// 物资汇总
<template>
    <div>
        <el-table
            class="table"
            :header-cell-style="{
                textAlign: 'center'
            }"
            :cell-style="{
                textAlign: 'center'
            }"
            :row-class-name="tableRowClassName"
            :data="materialsSummaryTableData"
            border
            style="width: 100%"
            :tree-props="{
                children: 'children',
                hasChildren: 'hasChildren'
            }"
            default-expand-all
            :max-height="$store.state.tableHeight"
            row-key="uuid"
            ref="table"
             v-sortTable="{ 'tableData': materialsSummaryTableData, '_this': this, 'ref': 'table' }"
        >
            <el-table-column label="操作" fixed width="100px" align="left">
                <template slot-scope="{ row, $index }">
                    <i
                        class="el-icon-delete"
                        style="cursor: pointer; font-size: 20px"
                        @click="deleteEle(row)"
                        v-if="$index > 0&&!isShow"
                    ></i>
                </template>
            </el-table-column>
            <el-table-column
                prop="materialClassName"
                label="物资类别"
                width="150"
            >
            </el-table-column>
            <el-table-column
                prop="materialName"
                label="物资名称"
                min-width="200"
            >
                <template slot-scope="scope">
                    <span
                        @click="clickMaterialName(scope.row)"
                        style="color: blue; cursor: pointer"
                    >
                        {{ scope.row.materialName }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="spec" label="规格型号" width="100">
            </el-table-column>
            <el-table-column prop="unit" label="计量单位" width="100">
            </el-table-column>
            <el-table-column prop="texture" label="材质" width="100">
            </el-table-column>
            <el-table-column prop="quantity" label="计划数量" width="100">
            </el-table-column>
            <el-table-column prop="amount" label="金额（元）" width="100">
            </el-table-column>

            <el-table-column
                prop="purchasingUnitName"
                label="集中采购单位"
                min-width="150"
            >
                <template slot="header">
                    <span>集中采购单位</span>
                    <i
                        v-if="materialsSummaryTableData.length > 0"
                        slot="suffix"
                        class="el-input__icon el-icon-document-copy"
                        style="cursor: pointer"
                        @click="collectUnitName"
                    ></i>
                </template>
                <template slot-scope="{ row, $index }">
                    <el-input
                        @input="input(row)"
                        v-model="row.purchasingUnitName"
                        v-if="$index > 0"
                    >
                        <i
                            slot="suffix"
                            class="el-input__icon el-icon-document-copy"
                            style="cursor: pointer"
                            @click="singUnitName(row)"
                        ></i>
                    </el-input>
                </template>
            </el-table-column>
            <el-table-column prop="purchaseType" label="采购方式" width="150">
                <template slot="header">
                    <span>采购方式</span>
                    <i
                        v-if="materialsSummaryTableData.length > 0"
                        slot="suffix"
                        class="el-input__icon el-icon-document-copy"
                        style="cursor: pointer"
                        @click="collectProcurementMethod"
                    ></i>
                </template>
                <template slot-scope="{ row, $index }">
                    <el-select
                        v-model="row.procurementMethod"
                        placeholder="请选择"
                        v-if="$index > 0"
                        @change="changeProcurementMethod(row)"
                    >
                        <el-option
                            v-for="item in procurementMethodArr"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </template>
            </el-table-column>
        </el-table>
        <!-- <span>
            {{ test }}
        </span> -->
        <!-- 机构汇总表 -->
        <el-table
            class="table"
            :data="materialsNameData"
            border
            style="width: 100%; margin-top: 20px"
            :header-cell-style="{
                textAlign: 'center'
            }"
            :cell-style="{
                textAlign: 'center'
            }"
            ref="table"
            v-sortTable="{ 'tableData': materialsNameData, '_this': this, 'ref': 'table' }"
        >
            <el-table-column prop="orgName" label="机构名称" min-width="200">
            </el-table-column>
            <el-table-column
                prop="materialName"
                label="物资名称"
                min-width="100"
            >
            </el-table-column>
            <el-table-column prop="spec" label="规格型号" width="100">
            </el-table-column>
            <el-table-column prop="unit" label="计量单位" width="100">
            </el-table-column>
            <el-table-column prop="texture" label="材质" width="100">
            </el-table-column>
            <el-table-column prop="quantity" label="计划数量" width="100">
            </el-table-column>
            <el-table-column prop="price" label="市场单价（元）" width="100">
            </el-table-column>
            <el-table-column prop="amount" label="金额（元）" width="100">
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex'
import planRequest from '@/api/turnover/plan.js'
import { getUuid } from '@/utils/common'
import { selectPurchaseType, getAllOrgPage } from '@/api/turnover/ppw'

export default {
    data () {
        return {
            test: [],
            annualDemandPlanBillIdArr: [],
            materialsSummaryTableData: [],
            materialsNameData: [] //点击物资名称获取子表
        }
    },
    created () {
        if (this.billId) {
            this.getSummaryTableData()
        }
    },
    computed: {
        ...mapState({
            planBillIdArr: state => state.turnover.planBillIdArr, //申报单位的billId
            materialsSummaryTableDataVuex: state =>
                state.turnover.materialsSummaryTableData, //表格汇总数据

            unitTableDataVuex: state => state.turnover.unitTableData, //表格汇总数据
            procurementMethodArr: state =>
                state.turnover.turnoverData.procurementMethod //采购方式
        })
    },
    props: {
        billId: {
            type: String,
            default: ''
        },
        isShow: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        planBillIdArr: {
            handler: function (cur) {
                if (cur) {
                    this.doSummary()
                }
            },
            deep: true
            // immediate: true
        }
    },
    methods: {
        ...mapMutations('turnover', [
            'setMaterialsSummaryTableData',
            'setUnitTableData'
        ]),
        //查询并保存汇总信息
        doSummary () {
            planRequest
                .turnoverCentralizedPurchaseSummaryGetAgencyListByOrgId(
                    this.planBillIdArr
                )
                .then(res => {
                    res.forEach(item => {
                        item.changeType = 1
                        item.billId = this.billId
                        this.annualDemandPlanBillIdArr.push(
                            item.annualDemandPlanBillId
                        )
                        // this.OrgtableData.push(item)
                    })
                    this.materialsSummaryTableDataAarry()
                })
        },
        // 查询保存后的物资汇总信息
        getSummaryTableData () {
            planRequest
                .turnoverCentralizedPurchaseSummaryGetSummarySetting(
                    this.billId
                )
                .then(res => {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(v => {
                            v.changeType = 2
                            v.billId = this.billId
                            v.uuid = getUuid()
                            v.parantId = item.uuid
                        })
                    })
                    this.setMaterialsSummaryTableData(res)
                    console.log(this.materialsSummaryTableDataVuex)
                    this.materialsSummaryTableData =
                        this.materialsSummaryTableDataVuex
                })
        },
        //根据总计划billid集合获取总计划明细集合
        materialsSummaryTableDataAarry () {
            planRequest
                .turnoverCentralizedPurchaseSummaryGetAllMaterial(
                    this.annualDemandPlanBillIdArr
                )
                .then(res => {

                    this.itemObj = {}
                    let count = 0
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(v => {
                            v.billId = this.billId
                            v.uuid = getUuid()
                            //汇总小计
                            count += v.amount
                            item.materialName = `小计： ${count.toFixed(2)}`
                        })
                        this.test = res
                        let i = 0
                        while (item.children[i + 1]) {
                            let j = i + 1
                            while (item.children[j]) {
                                if (
                                    item.children[i].materialClassId ===
                                        item.children[j].materialClassId &&
                                    item.children[i].materialId ===
                                        item.children[j].materialId &&
                                    item.children[i].texture ===
                                        item.children[j].texture
                                ) {
                                    item.children[i].quantity +=
                                        item.children[j].quantity
                                    item.children[i].amount +=
                                        item.children[j].amount

                                    // 下一元素与当前元素符合重复的条件，则叠加后删除下一元素
                                    item.children.splice(j, 1)
                                    j--
                                }
                                j++
                            }
                            i++
                        }
                    })

                    this.setMaterialsSummaryTableData(res)
                    this.materialsSummaryTableData = this.materialsSummaryTableDataVuex
                })
        },
        // 批量选择采购单位
        collectUnitName () {
            getAllOrgPage().then(val => {
                this.materialsSummaryTableData.forEach(a => {
                    a.children.forEach(c => {
                        c.purchasingUnitId = val.orgId
                        c.purchasingUnitName = val.orgName
                        this.reverseDtls(c, 1)
                    })
                })

                this.setMaterialsSummaryTableData(
                    this.materialsSummaryTableData
                )
            })
        },
        // 单个选择集中采购单位
        async singUnitName (row) {
            let data = await getAllOrgPage()
            row.purchasingUnitName = data.orgName
            row.purchasingUnitId = data.orgId
            this.reverseDtls(row, 1)
        },
        // 批量选择采购方式
        collectProcurementMethod () {
            selectPurchaseType().then(val => {
                this.materialsSummaryTableData.forEach(a => {
                    a.children.forEach(c => {
                        c.procurementMethod = Number(val.kvValue)
                        this.reverseDtls(c, 2)
                    })
                })

                this.setMaterialsSummaryTableData(
                    this.materialsSummaryTableData
                )
            })
        },
        // 改变采购方式事件
        changeProcurementMethod (row) {
            this.reverseDtls(row, 2)
            // 存储vuex
            this.setMaterialsSummaryTableData(this.materialsSummaryTableData)
        },
        // 汇总反写表格反写申报单位明细
        /**
         * type:1==>集中采购单位
         *      2==>采购方式
         */
        reverseDtls (row, type) {
            let arr = []
            this.unitTableDataVuex.forEach(v => {
                v.dtls.forEach(item => {
                    item.children.forEach(n => {
                        if (
                            n.materialClassId === row.materialClassId &&
                            n.materialId === row.materialId &&
                            n.texture === row.texture
                        ) {
                            if (type === 2) {
                                n.procurementMethod = row.procurementMethod
                            } else if (type === 1) {
                                n.purchasingUnitName = row.purchasingUnitName
                                n.purchasingUnitId = row.purchasingUnitId
                            }
                            n.orgName = v.orgName //用于
                            arr.push(n)
                        }
                    })
                })
            })

            this.setUnitTableData(this.unitTableDataVuex)
            return arr
        },
        // 点击汇总的物资名称 获取所有匹配的物资明细 展示此表
        clickMaterialName (row) {
            this.materialsNameData = this.reverseDtls(row)
        },
        // 删除汇总明细之后 所有相关明细都删除
        deleteEle (row) {

            row.changeType = -1
            this.unitTableDataVuex.forEach(v => {
                v.changeType = 2
                v.dtls.forEach(item => {
                    item.changeType = 2
                    item.children.forEach(n => {
                        if (
                            n.materialClassId === row.materialClassId &&
                            n.materialId === row.materialId &&
                            n.texture === row.texture
                        ) {
                            n.changeType = -1
                        }
                    })
                })
            })

            this.setUnitTableData(this.unitTableDataVuex)
            console.log(this.unitTableDataVuex)
            this.test = this.unitTableData
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        }
    }
}
</script>

<style lang="scss" scoped></style>
